package com.wanmait.computershop.webController;

import com.wanmait.computershop.dao.UserDAO;
import com.wanmait.computershop.dao.WebFavoritesDao;
import com.wanmait.computershop.vo.Product;
import com.wanmait.computershop.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("web")
public class WebLoginController {


    // 显示登录页面的方法
    @GetMapping("/login")
    public String showLoginPage() {
        return "web/login";  // 返回登录页面的视图名
    }

    // 处理登录请求的方法
    @PostMapping("/doLogin")
    @ResponseBody  // 因为要返回JSON给Ajax
    public Integer doLogin(HttpSession session, User user, HttpServletResponse response) {        
        UserDAO dao = new UserDAO();
        User loginUser = dao.login(user.getUsername(), user.getUserpass());
        if (loginUser != null) {
            //用户登录时调取喜欢商品
            WebFavoritesDao webFavoritesDao = new WebFavoritesDao();
            List<Product> productList = webFavoritesDao.findFavorByID(loginUser.getId());
            session.setAttribute("userFavorList", productList);
            
            session.setAttribute("loginUser", loginUser);
            Cookie cookie = new Cookie("loginUser", loginUser.getUsername());
            cookie.setMaxAge(604800);
            cookie.setPath("/");
            response.addCookie(cookie);
            return 200;
        } else {
            return 400;
        }
    }

    // 处理登出请求
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 清除session中的用户信息
        session.removeAttribute("loginUser");
        // 重定向到首页
        return "redirect:/web/index";
    }


}
